package hibernate.demo.secondlevelcache;


import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.chy.demo.secondlevelcache.entity.News;
import com.chy.query.hql.entities.Employee;

public class HibernateSecondLevelCache {
	
	private SessionFactory sessionFactory;
	private Session session;//这是为了测试才这样定义的，实际生产环境中，不能直接这样定义，否则会有并发问题
	private Transaction transaction;//这是为了测试才这样定义的，实际生产环境中，不能直接这样定义，否则会有并发问题

	@Before
	public void init(){
		Configuration configuration = new Configuration().configure();
		ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties())
																																	.buildServiceRegistry();
		sessionFactory = configuration.buildSessionFactory(serviceRegistry);
		
		session = sessionFactory.openSession();
		transaction = session.beginTransaction();
	}
	
	@After
	public void destory(){
		transaction.commit();
		session.close();
		sessionFactory.close();
	}
	
	@Test
	public void testSecondLevelCache(){
		
		News news = (News) session.get(News.class, 1);
		System.out.println(news.getAuthor());
		
		transaction.commit();
		session.close();
		
		session = sessionFactory.openSession();
		transaction = session.beginTransaction();
		
		News news2 = (News) session.get(News.class, 1);  
		System.out.println(news2.getAuthor());
		
	}
	
}
